//
//  RedBagVC.swift
//  LeGou
//
//  Created by lxm on 2022/10/8.
//

import UIKit

class RedBagVC: ZMViewController {

    //MARK:--------------------属性--------------------
    let openButtonWidth : CGFloat = 168
    
    var openFlag = false
        
    let redTimer = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
    
    var result : RedBagModels.RedRobResult?
    
    var redTimerDisposeBag = DisposeBag()
    
    @IBOutlet weak var froground_bottomH: NSLayoutConstraint!
    // 抢过的红包id数组
    var isPickedId = [Int]()
    
    //MARK:--------------------UI控件--------------------
    let coverImg = ZMUtil.imageView(imageName: "red_cover")
    
    let player = SVGAPlayer.init(frame: CGRect(x: 100, y: 100, width: rpx(324), height: rpx(452)))

    let openButton = ZMUtil.button()
    
    @IBOutlet weak var bottomCover: UIImageView!
        
    @IBOutlet weak var contentView: UIView!
    
    @IBOutlet weak var titleImg: UIImageView!
    
    var opened = ZMUtil.fastBehavior(value: false)
    
    let bottomInfoView = UIView()
    
    let beforeOpenLabel = ZMUtil.label(title: "周X 10:00-11:00 随机出现", color: .white, font: UIFont.systemFont(ofSize: 16, weight: .medium))
    
    let legxyhbImg = ZMUtil.imageView(imageName: "lgxyhb")
    
    let moneyLabel = ZMUtil.label(title: "88.00", color: Style.mainColor, font: Style.FONT_Open_Sans_SemiBold(62))
    
    let yuan = ZMUtil.imageView(imageName: "red_yuan")
    
    let timer = Observable<Int>.timer(.milliseconds(20), period: .milliseconds(10), scheduler: MainScheduler.instance)

    var timerDispose : Disposable?
    
    var distination : Double = 10.2
    // 红包记录面板
    var marqueeView = MarqueeView()
    
    var recordButton = ZMUtil.button(title: "幸运红包已到账余额钱包", font: UIFont.systemFont(ofSize: 16, weight: .medium), color: .white)
        
    let loading = XMLoadingView()
    
    weak var faildView : RedFailedView?
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        
        loading.showInView(fatherView: view)
        getRedScrollList()
        RedBagService.shared.getRedBagInfo()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        title = "百万红包"
        contentView.addSubview(coverImg)
         
        player.loops = 1
        player.clearsAfterStop = false
        let parser = SVGAParser()
        parser.parse(withNamed: "redBag", in: nil) { videoItem in
            self.player.videoItem = videoItem
        }
        
        contentView.insertSubview(player, belowSubview: bottomCover)
        player.fillMode = "Forward"
        player.delegate = self
        player.zm.setCenterX(SCREEN_W / 2)
        
        contentView.addSubview(openButton)
//        openButton.backgroundColor = UIColor.zm.RGBA(r: 0, g: 255, b: 0, a: 0.5)
        openButton.layer.cornerRadius = rpx(openButtonWidth) / 2
        openButton.layer.masksToBounds = true
                
        contentView.addSubview(bottomInfoView)
        bottomInfoView.layer.cornerRadius = 12
        bottomInfoView.layer.masksToBounds = true
        
        contentView.addSubview(beforeOpenLabel)
        
        contentView.addSubview(legxyhbImg)
        
        contentView.addSubview(moneyLabel)
        
        contentView.addSubview(yuan)
        
        contentView.addSubview(recordButton)
                
        setBottomView()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        print(SCREEN_W)
        print(SCREEN_H)
        if deviceIphoneX {
            // x
            player.zm.setBottom(contentView.zm.height - 80 - BottomSpace)
            froground_bottomH.constant = -15
        } else {
            player.zm.setBottom(contentView.zm.height - 114 - BottomSpace)
        }
        bottomInfoView.style.GradientLeftToRight(Top: "#FFFDED".zm.hex(), Bottom: "#FEEFCE".zm.hex())
    }
    
    func addConstraints() {
        coverImg.snp.makeConstraints { make in
            make.bottom.right.left.equalToSuperview()
        }
        
        openButton.snp.makeConstraints { make in
            make.width.height.equalTo(rpx(openButtonWidth))
            make.top.equalTo(player.snp.top).offset(rpx(130))
            make.centerX.equalToSuperview()
        }
        
        bottomInfoView.snp.makeConstraints { make in
            make.width.equalTo(rpx(343))
            make.height.equalTo(142)
            make.bottom.equalTo(self.contentView.safeAreaInsets.bottom).offset(-rpx(37))
            make.centerX.equalToSuperview()
        }
        
        beforeOpenLabel.snp.makeConstraints { make in
            make.top.equalTo(self.player.snp.top).offset(rpx(36 + 40))
            make.centerX.equalToSuperview()
        }
        
        legxyhbImg.snp.makeConstraints { make in
            make.top.equalTo(self.player.snp.top).offset(rpx(50))
            make.centerX.equalToSuperview()
        }
        
        moneyLabel.snp.makeConstraints { make in
            make.top.equalTo(legxyhbImg.snp.bottom).offset(4)
            make.centerX.equalToSuperview()
        }
        
        yuan.snp.makeConstraints { make in
            make.left.equalTo(moneyLabel.snp.right).offset(4)
            make.bottom.equalTo(moneyLabel.snp.lastBaseline)
            make.width.height.equalTo(24)
        }
        
        recordButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(self.player.snp.top).offset(rpx(280))
        }
    }
    
    func setBottomView() {
        let img = ZMUtil.imageView(imageName: "qhbxx")
        bottomInfoView.addSubview(img)
        img.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(16)
            make.width.equalTo(150)
            make.height.equalTo(22)
        }
        
        bottomInfoView.addSubview(marqueeView)
        
        marqueeView.snp.makeConstraints { make in
            make.top.equalTo(img.snp.bottom).offset(12)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-16)
        }
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        openButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if self.opened.value {return}
            RedBagService.shared.checkCanOpen { ok in
                if ok {
                    self.tryOpen()
                }
            }
        }).disposed(by: disposeBag)
        
        opened.subscribe(onNext:{ [unowned self] resp in
             
            if let r = self.result, r.state == 1 {
                // 抢完
                self.titleImg.image = UIImage.init(named: "red_hyh")
                self.yuan.isHidden = true
            } else {
                self.titleImg.image = UIImage.init(named: resp ? "gxn" : "hhpy")
                self.yuan.isHidden = !resp
            }
            
            self.titleImg.isHidden = false
            self.beforeOpenLabel.isHidden = resp
            self.legxyhbImg.isHidden = !resp
            self.moneyLabel.isHidden = !resp
            self.recordButton.isHidden = !resp
        }).disposed(by: disposeBag)
        
        marqueeView.needData = { [weak self] in
            guard let self = self else {return}
            self.getRedScrollList()
        }
        
        RedBagService.shared.redBagData.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            self.checkPicked(ids: resp.getIds())
        }).disposed(by: disposeBag)
    }
    
    func startTimer() {
        redTimerDisposeBag = DisposeBag()
        redTimer.subscribe(onNext:{ [unowned self] resp in
            guard let info = self.currentRedActivityInfo() else {self.beforeOpenLabel.text = ""; return}
            self.beforeOpenLabel.text = RedBagService.shared.suiteDes(info: info)
            self.recordButton.setTitle("下一轮" + RedBagService.shared.suiteDes(info: info), for: .normal)
            if let fv = faildView {
                fv.timeLabel.text = "下一轮" + RedBagService.shared.suiteDes(info: info)
            }
        }).disposed(by: redTimerDisposeBag)
    }
    
    func showSuccess() {
        guard let result = result else {return}
        let v = ZMUtil.loadNibViewFullScreen(nibName: RedSuccessView.self)
        v.money.text = result.amount.zm.toString(keep: 2, true)
        APPWindow?.addSubview(v)
    }
    
    func tryOpen() {
        guard let now = RedBagService.shared.redBagData.value?.now else {
            // 活动还未开始
            ZMToast.showToast(title: "当前没有进行中的红包活动")
            return
        }
        if let date = now.realStartTimeDate, date.timeIntervalSince1970 > RedBagService.shared.nowTimeinterval {
            ZMToast.showToast(title: "红包暂未开抢")
            return
        }
        if let date = now.realEndTimeDate, date.timeIntervalSince1970 < RedBagService.shared.nowTimeinterval {
            ZMToast.showToast(title: "本轮红包可抢时间已过")
            return
        }
        if openFlag {return}
        openFlag = true
        RedBagAPI.rob_bag(["activityId" : now.id]).rxRequest(type: RedBagModels.RedRobResult.self).subscribe(onNext:{ [unowned self] resp in
            if resp.state == 0 {
                // 成功
                self.result = resp
                self.isPickedId.append(now.id)
                if resp.type == 1 {
                    self.setRobed(result: resp)
                    self.showSuccess()
                } else {
                    self.showOpenAnimate()
                }
                RedBagService.shared.markActivityRobed(acId: now.id)
            } else if resp.state == 1 {
                // 抢完
                self.isPickedId.append(now.id)
                self.showFaild()
                self.setRobed(result: resp)
                self.openFlag = false
                RedBagService.shared.markActivityClicked(acId: now.id)
                RedBagService.shared.markActivityRobed(acId: now.id)
            } else if resp.state == 2 {
                // 抢过
                ZMToast.showToast(title: "您已经抢过红包了")
                self.openFlag = false
            }
        }, onError: { e in
            self.openFlag = false
        }).disposed(by: disposeBag)
    }
    
    func showOpenAnimate() {
        self.titleImg.isHidden = true
        self.beforeOpenLabel.isHidden = true
        self.player.startAnimation()
    }
    
    // 开红包成功
    func opensuccess() {
        guard let result = result else {return}
        opened.accept(true)
        if result.type == 1 {
            // 普通
            showSuccess()
            legxyhbImg.image = UIImage.init(named: "red_normal_icon")
        } else {
            legxyhbImg.image = UIImage.init(named: "lgxyhb")
        }
        changeText()
    }
    
    func showFaild() {
        let v = ZMUtil.loadNibViewFullScreen(nibName: RedFailedView.self)
        faildView = v
        APPWindow?.addSubview(v)
    }
    
    func changeText() {
        if let timerDispose = timerDispose {
            timerDispose.dispose()
        }
        guard let result = result else {return}
        var count = 0
        var from : Double = 0
        var to : Double = result.amount
        var durationCount = 75
        timerDispose = timer.subscribe(onNext:{ [weak self] resp in
            guard let self = self else {return}
            if count == durationCount {
                self.timerDispose?.dispose()
                self.moneyLabel.text = String(format: "%.2f", to)
                return
            }
            let v = self.easeIn(p: Double(count) / Double(durationCount)) * (to - from)
            self.moneyLabel.text = String(format: "%.2f", v)
            count += 1
        })
    }
    
    func easeIn(p : Double) -> Double {
        return p * p
    }
    
    
    @IBAction func onRobRank(_ sender: Any) {
        router.push("xm://main/RedBag/Rank/index", context: ["type" : 1])
    }
    
    @IBAction func onShareRank(_ sender: Any) {
        router.push("xm://main/RedBag/Rank/index", context: ["type" : 2])
    }
    
    // 校验当前红包有没有被抢
    func checkPicked(ids : [Int]) {
        var array = [Observable<RedBagModels.RedRobResult?>]()
        
        for id in ids {
            array.append(RedBagAPI.is_robed(["activityId" : id]).rxRequestNullAble(type: RedBagModels.RedRobResult.self))
        }
        
        Observable.combineLatest(array).subscribe(onNext:{ [unowned self] resp in
            if resp.count == 0 {return}
            for i in 0 ..< resp.count {
                if resp[i] != nil {
                    self.isPickedId.append(ids[i])
                }
            }
            if let r = resp[0] {
                // 当前第一个抢过了
                self.setRobed(result: r)
            } else if RedBagService.shared.isClicked(acId: ids[0]) {
                // 当前第一个抢过了，是失败的情况
                self.isPickedId.append(ids[0])
                let r = RedBagModels.RedRobResult()
                r.state = 1
                self.setRobed(result: r)
            } else {
                self.resetInfo()
            }
            self.startTimer()
            self.loading.hideView(anmation: true)
        }).disposed(by: disposeBag)
    }
    
    // 当前的场次
    func currentRedActivityInfo() -> RedBagModels.RedActivityInfo? {
        guard let redBagData = RedBagService.shared.redBagData.value else {return nil}
        if let now = redBagData.now, !isPickedId.contains(where: {$0 == now.id}), !RedBagService.shared.checkOver(info: now) {
            return now
        }
        if let wait = redBagData.wait, !isPickedId.contains(where: {$0 == wait.id}) {
            return wait
        }
        if let next = redBagData.next, !isPickedId.contains(where: {$0 == next.id}) {
            return next
        }
        return nil
    }
        
    // 设置为已经抢过的状态
    func setRobed(result : RedBagModels.RedRobResult) {
        self.result = result
        self.beforeOpenLabel.isHidden = true
        opened.accept(true)
        if result.state == 1 {
            // 抢完
            legxyhbImg.image = UIImage.init(named: "red_failed_icon")
        } else {
            if result.type == 1 {
                legxyhbImg.image = UIImage.init(named: "red_normal_icon")
            } else {
                legxyhbImg.image = UIImage.init(named: "lgxyhb")
            }
        }
        if result.amount == 0 {
            self.moneyLabel.font = UIFont.systemFont(ofSize: 46, weight: .semibold)
            self.moneyLabel.text = "已抢光"
        } else {
            self.moneyLabel.text = String(format: "%.2f", result.amount)
            self.moneyLabel.font = Style.FONT_Open_Sans_SemiBold(62)
        }
        player.step(toFrame: Int(player.videoItem.frames) - 2, andPlay: false)
    }
    
    // 重置页面信息
    func resetInfo() {
        self.yuan.isHidden = true
        self.titleImg.isHidden = false
        self.beforeOpenLabel.isHidden = false
        self.openFlag = false
        self.result = nil
        player.step(toFrame: 1, andPlay: false)
        self.opened.accept(false)
    }
    
    func getRedScrollList() {
        RedBagAPI.red_rank(["range" : 3, "type" : 1]).rxRequest(type: [RedBagModels.Rank].self).subscribe(onNext:{ [unowned self] resp in
            let r = resp.map { m in
                return (m.nickname + "    抢红包获得", "¥\(m.amount.zm.toString(keep: 2, true))")
            }
            if self.marqueeView.dataArray.count == 0 {
                self.marqueeView.reset(array: r)
            } else {
                self.marqueeView.dataArray.append(contentsOf: r)
                self.marqueeView.reload()
            }
        }, onError: { _ in
        }, onCompleted: {
        }).disposed(by: disposeBag)
    }
    
    @IBAction func onJoinRule(_ sender: Any) {
        CommonService.shared.goWeb(type: .redBagJoinRule)
    }
    
    //MARK:--------------------delegate--------------------
}

extension RedBagVC : SVGAPlayerDelegate {
    func svgaPlayerDidFinishedAnimation(_ player: SVGAPlayer!) {
//        player.stopAnimation()
//        if let item = player.videoItem {
//            player.setImage(item.images["redbaoone_00040"]!, forKey: "redbaoone_00040")
//        }
    }
    
    func svgaPlayer(_ player: SVGAPlayer!, didAnimatedToFrame frame: Int) {
        if frame == player.videoItem.frames - 2 {
            player.pauseAnimation()
            self.opensuccess()
        }
    }
}
